<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Call\Action\Dashboard;

use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Call\Logic\MonitorIndexLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 呼叫数据总览.
 * @Controller
 */
class CallList extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/call/callList", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        // 请求参数
        $data = $this->request->all();
        // 校验参数
        $this->validated($data);
        $list = Db::table('work_employee as employee')
            ->join('user as user', 'user.id', '=', 'employee.log_user_id')
            ->when(isset($data['keyword']) && $data['keyword'] !== '', function (Builder $query) use ($data) {
                $query->where(function (Builder $query) use ($data) {
                    $query->orWhere('user.extn', '=', $data['keyword']);
                    $query->orWhere('employee.name', 'like', "%" . $data['keyword'] . "%");
                });
            })
            ->whereNotNull('user.extn')
            ->where('user.extn','<>','')
            ->select([
                'employee.id',
                'employee.name',
                'user.extn',
            ])
            ->paginate((int)($data['perPage'] ?? 15));
        $list || $list = collect([]);
        $list = $list->toArray();


        $token = send_http_request(env("CALL_CENTER_BASE_URL"), '/api/login', 'GET', [
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'verify' => false,
            'query' => [
                'username' => env("CALL_CENTER_USERNAME"),
                'password' => env("CALL_CENTER_PASSWORD"),
            ]
        ]);

        $response = send_http_request(env("CALL_CENTER_BASE_URL"), '/api/ola/agents', 'GET', [
            'headers' => [
                'X-Auth-Token' => $token,
                'Content-Type' => 'application/json',
            ],
            'verify' => false,
            // 'query' => [
            //     'extn' => $params['extn'],
            // ]
        ]);
        $dataOne = my_array_change_key($response);
        $totalCount=$dataOne['count']??0;
        $dataOne = array_column($dataOne['agents'],null,'extn');

        $states=empty($dataOne)?[]:array_column($dataOne,'state');
        $statesCount=empty($states)?[]: array_count_values($states);
        if (!empty($list['data'])) {
            $workEmployeeIds = array_column($list['data'], 'id');
            $query = Db::table('call_record')
                ->whereIn('work_employee_id', $workEmployeeIds);
            $total = $query->select([
                Db::raw('COUNT(*) as count'),
                'work_employee_id',
                Db::raw('SUM(call_duration) as call_duration')
            ])->groupBy([
                'work_employee_id'
            ])->get();
            $total || $total = collect([]);
            $total = $total->toArray();
            $total = empty($total) ? [] : array_column($total, null, 'work_employee_id');
            foreach ($list['data'] as &$datum) {
                $key = $datum->id;
                //外呼总数
                $datum->callTotal = $total[$key]->count ?? 0;
                //外时长秒
                $datum->callDuration = $total[$key]->call_duration ?? 0;
                $hour = floor($datum->callDuration / 3600);
                $hour = str_pad((string)$hour, 2, "0", STR_PAD_LEFT) . ':';
                $surplus = $datum->callDuration % 3600;
                $minute = floor($surplus / 60);
                $minute = sprintf('%02d', $minute) . ':';
                $seconds = $surplus % 60;
                $seconds = sprintf('%02d', $seconds);
                $datum->callDuration = $hour . $minute . $seconds;


                $datum->statusString = "示闲";
                $datum->statusTime = "00:00:00";
                if (isset($dataOne[$datum->extn]['updatedAt']) && $dataOne[$datum->extn]['updatedAt']) {
                    $totalSeconds = time() - strtotime($dataOne[$datum->extn]['updatedAt']);
                    //小时
                    $hour = floor($totalSeconds / 3600);
                    $hourSurplusSeconds = $totalSeconds - ($hour * 3600);
                    //分钟
                    $minutes = floor($hourSurplusSeconds / 60);
                    //秒
                    $seconds = $hourSurplusSeconds - ($minutes * 60);
                    //闲置时间
                    $datum->statusTime = $hour . ":" . $minutes . ":" . $seconds;
                }

                if (isset($dataOne[$datum->extn]['state'])) {
                    if ($dataOne[$datum->extn]['state']=='logout'){
                        $datum->statusString = '离线';
                    }
                    if ($dataOne[$datum->extn]['state']=='ready'){
                        $datum->statusString = '示闲';
                    }
                    if ($dataOne[$datum->extn]['state']=='unready'){
                        $datum->statusString = '示忙';
                    }
                    if ($dataOne[$datum->extn]['state']=='busy'){
                        $datum->statusString = '通话中';
                    }
                    if ($dataOne[$datum->extn]['state']=='acw'){
                        $datum->statusString = '整理中';
                    }
                }
            }
            unset($datum);
            $list['callTotalNumber']= $totalCount;
            $list['idleNumber'] =$statesCount['ready']??0 ;//示闲
            $list['busyNumber'] = $statesCount['unready']??0;//示忙
            $list['offLineNumber'] = $statesCount['logout']??0;//离线
        }
        return $list;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'type' => 'in:1,2,3,4,5',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'type.in' => 'type参数值错误',
        ];
    }
}
